﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using YiSha.Entity.QixingManage;
using YiSha.Enum.QixingManage;
using YiSha.Model.Param.QixingManage;
using YiSha.Service.QixingManage;
using YiSha.Util.Model;

namespace YiSha.Business.AutoJob.Job
{
    public class OrderJob : IJobTask
    {
        private OrderMasterService orderMasterService = new OrderMasterService();
        private GoodsWarehouseService goodsWarehouseService = new GoodsWarehouseService();
        private OrderDetailService orderDetailService = new OrderDetailService();

        public async Task<TData> Start()
        {
            TData obj = new TData();
            //获取全待支付过期的订单
            var orders=orderMasterService.GetList(new OrderMasterListParam() { invalidorder = true });
            List<OrderMasterEntity> uplist=new List<OrderMasterEntity>();
            foreach (var item in orders.Result)
            {
                item.order_status = ((int)orderStatus_enum.无效订单);
                uplist.Add(item);

                //待还原库存，需要加锁控制，后期处理 需要配合事务处理
                //select * from t where id >10 and id <=15 for update;
                var orderDetail=orderDetailService.BaseRepository().FindEntity<OrderDetailEntity>(t=>t.order_id==item.Id).Result;
                if (orderDetail!=null) 
                {
                    await goodsWarehouseService.BaseRepository().BeginTrans();

                    var pw=goodsWarehouseService.BaseRepository().FindObject<GoodsWarehouseEntity>(string.Format(@"select * from goods_warehouse where Id={0} for update", orderDetail.pw_id)).Result;

                    if (pw!=null)
                    {
                        pw.current_cnt = pw.current_cnt + orderDetail.goods_cnt;

                       await goodsWarehouseService.SaveForm(pw);
                    }
                    await goodsWarehouseService.BaseRepository().CommitTrans();

                }
            }

            await orderMasterService.BaseRepository().Update(uplist);

            obj.Tag = 1;
            obj.Message = "失效订单刷新成功";
            return obj;
        }
    }
}
